/* eslint-disable */
'use strict'

const express = require('express')
const router = express.Router()
const dbconnection = require('../config/database.js')
const log4js = require('log4js')
const logger = log4js.getLogger('queryInfos')


const queryInfos = (page, pagesize, flag, callback) => {
  //分页查询逻辑
  let sqlStr = `select * from infos WHERE flag = "${flag}" limit ${(page-1)*pagesize}, ${pagesize}`
  console.log(sqlStr)
  dbconnection.execute(sqlStr, callback)
}
const queryTotal = (flag, callback) => {
  console.log(flag)
  dbconnection.execute('SELECT count(*) FROM infos WHERE flag = ?',flag, callback)
}
const queryInfosPromise = (page, pagesize, flag) => new Promise((resolve, reject) => {
  queryInfos(page, pagesize, flag, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})
const queryTotalPromise = (flag) => new Promise((resolve, reject) => {
  queryTotal(flag, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})
/* POST execl listing. */
router.post('/', (req, res, next) => {
  if (req.session.uuid !== req.cookies.uuid || !req.session.uuid) {
    logger.error(req.session.uuid, req.cookies.uuid)
    return res.send({rtnCode:'302', rtnMsg: '登录过期，请重新登录'});
  }
  Promise.all([queryInfosPromise(req.body.page, req.body.pagesize, req.session.flag), queryTotalPromise(req.session.flag)]).then(([infoRes, totalRes]) => {
    let results = {
      infos: infoRes,
      total: totalRes[0]['count(*)']
    }
    logger.info(results)
    results.infos.forEach((e, i) => {
      delete e.flag
    })
    res.send({rtnCode: '000',results: results, rtnMsg: '查询信息成功'});
  }).catch(err => {
    logger.error(err)
    res.status(500).send({rtnCode: '500', rtnMsg: '服务器错误'})
  })
});


module.exports = router;
